package com.lemo.juc;

import java.util.concurrent.CountDownLatch;

/*
 * 
    * @className: CountDownLatchDemo
    * @description: 闭锁 子线程都运算完成在运算总线程
    * @author liming
    * @date 2017年2月9日 上午11:34:33
    *
 */
public class CountDownLatchDemo {

	public static void main(String[] args) {

		final CountDownLatch latch = new CountDownLatch(5);

		LatchDemo latchDemo = new LatchDemo(latch);

		long s = System.currentTimeMillis();

		for (int i = 0; i < 5; i++) {
			new Thread(latchDemo).start();
		}

		try {
			latch.await();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		
		long e = System.currentTimeMillis();
		
		System.out.println("运行时间：" + (e - s));

	}
}

class LatchDemo implements Runnable {

	private CountDownLatch latch;

	public LatchDemo(CountDownLatch latch) {
		this.latch = latch;
	}

	@Override
	public void run() {

		synchronized (this) {
			try {
				for (int i = 0; i < 50000; i++) {
					if (i % 2 == 0) {
						System.out.println(i);
					}
				}
			} finally {
				latch.countDown(); // 减1
			}
		}
	}

}
